package t2dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import t2bean.BookBean;
import t2jdbc.JDBCUtil;

public class BookDao extends Dao {
	private SetSql ss = new SetSql();

	public int insert(BookBean book) {
		String sql = "insert into book(bookid,name,islended,lendtimes) values(?,?,?,0)";
		List<Object> list = new ArrayList<>();
		list.add(book.getBookId());
		list.add(book.getName());
		list.add(book.getIsLended());
		int back = 0;
		try {
			back = dml(sql, list);
			return back;
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return 0;
	}

	public int update(BookBean book) {
		List<Object> list = new ArrayList<>();
		String sql = "update book set ";
		sql = ss.setSql(book, sql, list, 1);
		sql+=" where bookid=?";
		list.add(book.getBookId());
//		System.out.println(sql);
		int back = 0;
		try {
			back = dml(sql, list);
			return back;
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return 0;
	}

	public List<BookBean> select(BookBean book) throws SQLException {
		String sql;
		List<BookBean> backList = new ArrayList<>();
		List<Object> list = new ArrayList<>();
		ResultSet rs = null;
		if (book != null) {
			sql = "select * from book where ";
			sql = ss.setSql(book, sql, list, 2);
//			System.out.println(sql);
		} else {
			sql = "select * from book";
		}

		try {
			rs = dql(sql, list);
			while (rs.next()) {
				BookBean book1 = new BookBean();
				book1.setId(rs.getInt("id"));
				book1.setBookId(rs.getInt("bookid"));
				book1.setName(rs.getString("name"));
				book1.setIsLended(rs.getInt("islended"));
				book1.setLendTimes(rs.getInt("lendtimes"));
				backList.add(book1);
			}
			return backList;
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			JDBCUtil.close(super.conn, super.ps, super.rs);
			super.conn = null;
			super.ps = null;
			super.rs = null;
			rs.close();
			rs = null;
		}
		return null;
	}
}
